//
//  HRActivityInfoViewController.m
//  haierapp
//
//  Created by gaotangzhang on 14-8-15.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRActivityInfoViewController.h"
#import "HROrderInfoViewController.h"
#import "HRAppDelegate.h"

#import "WebViewJavascriptBridge.h"

#import "HRActivityInfo.h"
#import "HRGoodsInfoList.h"

#define WEB_METHOD_RESERVATION @"clickReservationsNow"

@interface HRActivityInfoViewController (){
    UIWebView *cacheWebView;    //缓存参数页面
}

@property(nonatomic,strong) WebViewJavascriptBridge *bridge;

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation HRActivityInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title=_productName;
    
    [self initWebJavscriptBridge];
    
    if (![_urlStr isEqualToString:@""]) {
        [self showCustomLoadingHud:kLoading inView:nil];
        
        NSURL *url=[NSURL URLWithString:_urlStr];
        [self.webView loadRequest:[NSURLRequest requestWithURL:url] progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        } success:^NSString *(NSHTTPURLResponse *response, NSString *HTML) {
            [self hideCustomLoadingHud];
            
            //解决参数页面不能点击
            [self cacheProductParamWebView];
            
            return HTML;
        } failure:^(NSError *error) {
            [self showTextHUD:error.description];
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//初始化构建Bridge控件
-(void)initWebJavscriptBridge{
    _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView webViewDelegate:self handler:nil];
    
    //预定商品
    [_bridge registerHandler:WEB_METHOD_RESERVATION handler:^(id data, WVJBResponseCallback responseCallback) {
        [self reservationProduct:data];
    }];
    
}

//加载测试html页面
- (void)loadExamplePage:(UIWebView*)webView {
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"activityinfo" ofType:@"html"];
    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [_webView loadHTMLString:appHtml baseURL:baseURL];
}

//缓存商品参数URL (解决WAP页面按钮，第一次加载不能点击)
-(void)cacheProductParamWebView{
    
    NSString *urlStr=URL_WAP_GOODS_PARAMS(_productId);
    NSURL *url=[NSURL URLWithString:urlStr];
    
    cacheWebView = [[UIWebView alloc]init];
    
    [self showCustomLoadingHud:kLoading inView:nil];
    [cacheWebView loadRequest:[NSURLRequest requestWithURL:url] progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        
    } success:^NSString *(NSHTTPURLResponse *response, NSString *HTML) {
        [self hideCustomLoadingHud];
        return HTML;
    } failure:^(NSError *error) {
        [self hideCustomLoadingHud];
    }];
    
}

#pragma mark - Methods

//“立即预定”功能
-(void)reservationProduct:(NSString *)param{
    
    HRUser *user = [HRCommonData shareCommonData].curUser;
    
    if (user == nil) {
        //未登陆
        [kAppDelegate showUserLoginCompletion:^{
        } ];
        
        return;
    }
    
    HRActivityInfo *activityInfo=[[HRActivityInfo alloc]initWithString:param error:nil];
    
    //获取商品数据
    int count=0;
    NSMutableString *productIds=[NSMutableString stringWithString:@""];
    if (activityInfo.productIdList!=nil && [activityInfo.productIdList count]>0) {
        count=[activityInfo.productIdList count];
    }
    
    //该活动没有商品
    if (count==0) {
        return;
    }
    
    for (int i=0; i<count; i++) {
        HRActivityProduct *product=[activityInfo.productIdList objectAtIndex:i];
        
        [productIds appendString:product.productId];
        
        if (i<(count-1)) {
            [productIds appendString:@","];
        }
    }
    
    [self showCustomLoadingHud:kLoading inView:nil];
    [HRInterfaceManager getProductListByIDList:productIds completion:^(BOOL isSucceed, NSString *message, id data) {
        
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            HRGoodsInfoList *goodsList=(HRGoodsInfoList *)data;
            
            NSMutableArray *productList=[NSMutableArray array];
            
            for (HRGoodsInfo *goodsInfo in goodsList.list) {
                HRProductInfo *productInfo=[[HRProductInfo alloc]initWithGoodsInfo:goodsInfo];
                
                //获取商品数量
                for (HRActivityProduct *activeProduct in activityInfo.productIdList) {
                    if ([activeProduct.productId isEqualToString:productInfo.productId]) {
                        int goodsCount=[activeProduct.productNum intValue];
                        productInfo.goodsAmount=@(goodsCount);
                        
                        CGFloat price=[activeProduct.productPrice floatValue];
                        productInfo.price = @(price);
                    }
                }
                
                //加入订单产品列表中
                [productList addObject:productInfo];
            }
            
            //进入订单确认页面
            //订单确认页面
            HROrderInfoViewController *viewC = [[HROrderInfoViewController alloc] initWithNibName:NIBNAME_ORDER_INFO bundle:nil];
            viewC.arrayGoods = productList ;
            viewC.activityId = activityInfo.activityId;
            viewC.prePayment = activityInfo.advancePayment;//预付款
            viewC.lastPayment = activityInfo.tailPayment;//尾款
            viewC.totalPrice = activityInfo.activityPrice;//活动全款
            viewC.type=ORDER_CONFIRM_TYPE_ACTIVITY;//活动订单
            
            viewC.activityType = [activityInfo.isActivity intValue];
            
            [self.navigationController pushViewController:viewC animated:YES];

            
        }else{
            [self showTextHUD:message];
        }
        
    }];
    

}

#pragma mark - GoodsParam Delegate Methods
//预定商品，设置的参数
-(void)buyGoodsSetParam:(NSString *)goodsParam{
    NSDictionary *paramDic=[goodsParam toArrayOrDictionary];
    
    //生成订单
    NSString *activityId=[paramDic objectForKey:@"productId"];
    BOOL hasGoods=[[paramDic objectForKey:@"inventory"] boolValue];
    
    if (!hasGoods) {
        //配送地区没有货
        [self showTextHUD:@"配送地区没有货"];
        return;
    }
    
    
    
}

//在服务器添加商品到购物车
-(void)addProductInCarToServer:(NSString *)productId{
    [self showCustomLoadingHud:kLoading inView:nil];
    
    //添加到购物车
    [HRInterfaceManager addProductToShopCar:productId completion:^(BOOL isSucceed, NSString *message, id data) {
        [self hideCustomLoadingHud];
        if (isSucceed) {
            [self showSuccessHud:@"添加购物车成功"];
        }else{
            [self showTextHUD:message];
        }
    }];
}

//在本地缓存添加商品到购物车
-(void)addProductInCarToCache:(NSString *)productId{
    
    [self showCustomLoadingHud:kLoading inView:nil];
    
    //从购物车获取商品信息
    [HRInterfaceManager getProductById:productId completion:^(BOOL isSucceed, NSString *message, id data) {
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            HRGoodsInfo *goodsInfo=(HRGoodsInfo *)data;
            
            [[HRCommonData shareCommonData] addProductToShopCar:goodsInfo andProductId:productId];
            
            [self showSuccessHud:@"添加购物车成功"];
        }else{
            [self showTextHUD:message];
        }
    }];
    
}


@end
